<?php

ini_set("memory_limit", "100M");
ini_set("max_execution_time", 36000);

require_once('../../config/maptrick.conf.php');
require_once(SITE_ROOT . "config/session.php");
require_once(SITE_ROOT . 'lib/PHT.php');
require_once(SITE_ROOT . 'class/bean/Country.class.php');
require_once(SITE_ROOT . 'class/bean/Division.class.php');
require_once(SITE_ROOT . 'class/bean/League.class.php');
require_once(SITE_ROOT . 'class/bean/Team.class.php');
require_once(SITE_ROOT . 'class/db/DBCountry.class.php');
require_once(SITE_ROOT . 'class/db/DBDivision.class.php');
require_once(SITE_ROOT . 'class/db/DBLeague.class.php');
require_once(SITE_ROOT . 'class/db/DBTeam.class.php');
require_once(SITE_ROOT . 'class/logic/LogicCoolness.class.php');

try {
	if ($_GET["pass"] != SCRIPT_PWD) die("Incorrect password");
	
	$HT = new CHPPConnection(CONSUMERKEY, CONSUMERSECRET);
	$HT->setOauthToken(USERTOKEN);
	$HT->setOauthTokenSecret(USERTOKENSECRET);
	
	$_SESSION['HT'] = $HT;
	
	$dbcountry = new DBCountry();
	$dbdivision = new DBDivision();
	$dbleague = new DBLeague();
	$dbteam = new DBTeam();
	$logic = LogicCoolness::getInstance();
	$count = 0;
		
	$countries = $dbcountry->getCountries();
	foreach ($countries as $country) {
		if ($country->getCountryID() == 39) {
		//if ($country->getActiveUsers() >= 3600 && $country->getActiveUsers() < 1000000000) {
			$divisions = $dbdivision->getDivisionsByCountry($country, true);
			foreach ($divisions as $division) {
				//if ($division->getDivisionID() == 1) {
					$leagues = $dbleague->getLeaguesByDivision($division);
					foreach ($leagues as $league) {
						$teams = $dbteam->getTeamsByLeague($league);
						foreach ($teams as $team) {
							//if ($team->getOrFlags() <= 124 && $team->getOrFlags() >= 120) {
							//if ($team->getHomeCoolness() > 800000.00) {
							//if (date("Y", $team->getUpdate()) == 1970) {
							//if (date("Y", $team->getUpdate()) == 1970 && date("m", $team->getUpdate()) == 01) {
							//if (substr($team->getActivationDate(), 0, 4) == 1997) {
								try {
									$logic->autoUpdate($team->getTeamID(), false);
									$count++;
									if ($count == 100) {
										$HT->clearLeagues();
										$HT->clearTeams();
										$count = 0;
									}
								}
								catch (IsBotException $ibe) {}
								catch (LeagueNotAvailableException $lnae) {}
								catch (Exception $e) {
									echo "Update failed at team " . $team->getTeamID() . "<br />";
								}
							//}
						}
					}
				//}
			}
			echo $country->getName() . " done<br />";
		}	
	}
	echo "Update was successfull!";
}
catch (Exception $e) {
	echo $e->getMessage();
}

?>